import * as dotenv from 'dotenv'
import { resolve } from 'path'

const path = resolve(__dirname, '../configs.env')

dotenv.config({ path })

export const env: IEnv = {
  DATABASE_URL: process.env.DATABASE_URL!,
  NODE_SERVER_PORT: process.env.NODE_SERVER_PORT!,
  NODE_ENV: process.env.NODE_ENV! as 'development' | 'production',
  JWT_SECRET: process.env.JWT_SECRET!,
  REDIS_HOST: process.env.REDIS_HOST!,
  REDIS_PORT: process.env.REDIS_PORT!,
  DATABASE_USER: process.env.DATABASE_USER!,
  DATABASE_HOST: process.env.DATABASE_HOST!,
  DATABASE_NAME: process.env.DATABASE_NAME!,
  DATABASE_PASSWD: process.env.DATABASE_PASSWD!,
  DATABASE_PORT: process.env.DATABASE_PORT!,
  WX_APP_ID: process.env.WX_APP_ID!,
  WX_APP_SECRET: process.env.WX_APP_SECRET!,
  GRANTTYPE: process.env.GRANTTYPE! as 'authorization_code' | 'client_credential',
  TEST_USER: process.env.TEST_USER!,
  TEST_USER_PASSWORD: process.env.TEST_USER_PASSWORD!,
}

export interface IConfig {
  port: number
  debugLogging: boolean
  dbsslconn: boolean
  jwtSecret: string
  databaseUrl: string
  tokenExpiresTime: number
}

// 允许跨域的 host
export const whiteHostSet = new Set(['localhost:9000', '127.0.0.1:9000'])

export const PROTO_PATH = resolve(__dirname, `${process.env.PROTO_PATH_ENV}`)

export const config: IConfig = {
  port: +env.NODE_SERVER_PORT,
  debugLogging: env.NODE_ENV === 'development',
  dbsslconn: env.NODE_ENV !== 'development',
  jwtSecret: env.JWT_SECRET,
  databaseUrl: env.DATABASE_URL,
  tokenExpiresTime: 1000 * 60 * 60 * 24 * 7
}

export const redisConfig: RedisOptions = {
  host: env.REDIS_HOST,
  port: +env.REDIS_PORT,
}

export const wxappConfigs: WxappConfig = {
  appid: env.WX_APP_ID,
  secret: env.WX_APP_SECRET,
  grantType: env.GRANTTYPE
}

export const connectionOptions: DatabaseOptions = {
  database: env.DATABASE_NAME,
  host: env.DATABASE_HOST,
  password: env.DATABASE_PASSWD,
  port: +env.DATABASE_PORT,
  username: env.DATABASE_USER,
  entities: [
    process.env.NODE_ENV === 'development' ? resolve(__dirname, 'entity/**/*.ts') : resolve(__dirname, 'entity/**/*.js')
  ]
}

export const adminConfig: { password: string, username: string } = {
  password: env.TEST_USER_PASSWORD,
  username: env.TEST_USER
}

export const RpcConfig = {
  host: 'locahost',
  port: ':50052'
}
